package com.tanhua.server.interceptor;

import com.alibaba.fastjson.JSON;
import com.tanhua.model.db.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 统一处理token拦截器类
 */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     *进入controller之前 进行登录校验处理
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //记录请求的路径
        String requestMethod = request.getMethod();
        log.info("请求了路径: {}:{}",requestMethod, request.getRequestURI());
        if(handler instanceof HandlerMethod) {
            // 找出调用的哪个controller中的方法
            HandlerMethod method = (HandlerMethod) handler;
            if(null != method) {
                log.info("执行了: " + method.getShortLogMessage());
            }
        }


        //1.获取请求头中token
        String headToken = request.getHeader("Authorization");
        //2.根据key 获取redis中userStr
        String tokenKey = "TOKEN_" + headToken;
        String userStr = stringRedisTemplate.opsForValue().get(tokenKey);
        //3 如果userStr为空 直接返回权限不足 return false;
        if(StringUtils.isEmpty(userStr)){
            //响应码设置为401：权限不足
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        //4 如果userStr不为空 得到user对象
        User user = JSON.parseObject(userStr, User.class);
        //5.将user对象存入ThreadLocal中
        UserHolder.setUser(user);
        log.debug("*******登录验证成功了*********"+userStr+"*********************");
        return true;
    }

    /**
     * controller发生异常，照样执行
     * 移除线程中的对象
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }
}
